package com.hb.trade.api.push.task.tenderbulletinphase;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.hb.core.pojo.Attachments;
import com.hb.core.pojo.OrganizeInfo;
import com.hb.core.pojo.enums.NoticeNatureEnum;
import com.hb.core.pojo.project.notice.dto.NoticeDTO;
import com.hb.core.pojo.project.notice.entity.NoticeBidSection;
import com.hb.core.pojo.project.proj.entity.AbstractProject;
import com.hb.core.pojo.project.section.dto.BidSectionDTO;
import com.hb.trade.api.push.config.PushDataConfig;
import com.hb.trade.api.push.task.tenderprojectphase.BidSectionPushS;
import com.hb.trade.api.push.task.tenderprojectphase.TenderAgency;
import com.hb.trade.api.push.task.tenderprojectphase.Tenderer;
import com.hb.trade.api.push.util.ConstantUtil;
import com.hb.trade.api.push.util.PushUtil;
import com.hb.trade.api.push.util.SFTPUtils;
import com.hb.trade.client.project.ProjectClient;
import com.jcraft.jsch.SftpException;
import lombok.Data;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.util.Enums;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * describe:
 * 公告推送相关的数据模型
 * @author zhongdl
 * @date 2022/02/23
 */
@Data
public class TenderBulletinPhase {

    /**
     * 招标项目编号
     */
    @JsonProperty("TENDER_PROJECT_CODE")
    private String tenderProjectCode;

    /**
     * 标段code列表
     */
    @JsonProperty("BID_SECTION_CODES")
    private BidSectionPushS bidSectionCodes;
    /**
     * 招标编号
     */
    @JsonProperty("TENDER_CODE")
    private String tenderCode;
    /**
     * 公告名称
     */
    @JsonProperty("NOTICE_NAME")
    private String noticeName;

    /**
     * 公告内容文本
     */
    @JsonProperty("NOTICE_CONTENT")
    private String noticeContent;
    /**
     * 公告发布时间
     */
    @JsonProperty("NOTICE_SEND_TIME")
    private String noticeSendTime;
    /**
     * 公告发布媒介
     */
    @JsonProperty("NOTICE_MEDIA")
    private String noticeMedia;

    /**
     * 源URL
     */
    @JsonProperty("URL")
    private String url;
    /**
     * 公告性质
     */
    @JsonProperty("NOTICE_NATURE")
    private String noticeNature;
    /**
     * 公告类型
     */
    @JsonProperty("NOTICE_TYPE")
    private String noticeType;

    /**
     * 招标文件/资格预审文件获取开始时间
     */
    @JsonProperty("DOC_GET_START_TIME")
    private String docGetStartTime;
    /**
     * 招标文件/资格预审文件获取截止时间
     */
    @JsonProperty("DOC_GET_END_TIME")
    private String docGetEndTime;
    /**
     * 招标文件/资格预审文件获取方法
     */
    @JsonProperty("DOC_GET_METHOD")
    private String docGetMethod;

    /**
     * 投标文件/资格预审申请文件递交截止时间
     */
    @JsonProperty("BID_DOC_REFER_END_TIME")
    private String bidDocReferEndTime;
    /**
     * 投标文件/资格预审申请文件递交方法
     */
    @JsonProperty("BID_DOC_REFER_METHOD")
    private String bidDocReferMethod;

    /**
     * 投标文件/资格预审申请文件递交方法
     */
    @JsonProperty("BID_URL")
    private String bidUrl;



    /**
     * 是否允许联合体投标
     */
    @JsonProperty("SYNDICATED_FLAG")
    private String syndicatedFlag;


    /**
     * 是否延期
     */
    @JsonProperty("IS_POSTPONE")
    private String isPostpone;

    /**
     * 开标时间
     */
    @JsonProperty("BID_OPEN_TIME")
    private String bidOpenTime;

    /**
     * 开标/开启方式
     */
    @JsonProperty("BID_OPEN_METHOD")
    private String bidOpenMethod;
    /**
     * 开标/开启方式
     */
    @JsonProperty("QUAL_TYPE")
    private String qualType;


    @JsonProperty("TENDERERS")
    private List<Map<String, Tenderer>> tenderers;


    @JsonProperty("TENDER_AGENCYS")
    private List<Map<String, TenderAgency>> tenderAgencies;

    /**
     * 公告发布责任人
     */
    @JsonProperty("BULLETIN_DUTY")
    private String bulletinDuty;
    /**
     * 交易平台数据验证责任人姓名
     */
    @JsonProperty("EXAMINER_NAME")
    private String examinerName;

    /**
     * 附件列表
     */
    @JsonProperty("ATTACHMENT_SET")
    private List<Map<String,AttachmentSet>> attachmentSets;


    /**
     *交易平台或发布工具标识码
     */
    @JsonProperty("TRADE_PLAT")
    private String tradePlat;

    /**
     *公共服务平台标识码
     */
    @JsonProperty("PUB_SERVICE_PLAT_CODE")
    private String pubServicePlatCode;

    /**
     *数据时间戳
     */
    @JsonProperty("SUBMIT_TIMESTAMP")
    private String submitTimestamp;

    public TenderBulletinPhase(NoticeDTO noticeDTO) throws SftpException, IOException {
        //上传附件
        Attachments signFile = noticeDTO.getSignFile();
        if (CollUtil.isEmpty(signFile)){
            return;
        }
        String fileUrl = signFile.get(0).getFileUrl();
        boolean save = SFTPUtils.uploadFile(fileUrl);
        if (!save){
            return;
        }
        AttachmentSet attachmentSet = new AttachmentSet();
        attachmentSet.setAttachmentCode(PushUtil.getUuid());
        attachmentSet.setAttachmentFileName(FileUtil.getName(fileUrl).replaceAll("-",""));
        attachmentSet.setFileType("TENDER_NOTICE_FILE");
        attachmentSet.setDataTimestamp(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        attachmentSet.setMd5(SFTPUtils.getMD5(fileUrl));
        ProjectClient projectClient = SpringUtil.getBean(ProjectClient.class);

        AbstractProject project = new AbstractProject();
        project.setId(noticeDTO.getProjectId());
        project.setWithSections(Boolean.TRUE);
        Message<AbstractProject> abstractProjectMessage = projectClient.projectDetail(project);
        if (abstractProjectMessage.isFail() || abstractProjectMessage.getData() == null){
            return;
        }
        project = abstractProjectMessage.getData();
        BidSectionPushS bidSectionPushS = new BidSectionPushS();
        List<String> bidSectionCodeList = CollUtil.list(false);
        //查询标段列表
        if (CollUtil.isNotEmpty(project.getSections()) && CollUtil.isNotEmpty(noticeDTO.getNoticeBidSections())){
            List<Long> sectionIdList = noticeDTO.getNoticeBidSections().stream().
                    map(NoticeBidSection::getSectionId).collect(Collectors.toList());
            List<BidSectionDTO> sections = project.getSections();
            int size = project.getSections().size();
            for (int i = 0; i < size; i++) {
                BidSectionDTO bidSectionDTO = sections.get(i);
                if (!sectionIdList.contains(bidSectionDTO.getId())){
                    continue;
                }
                bidSectionCodeList.add(bidSectionDTO.getSectionCode());
            }

        }
        bidSectionPushS.setBidSectionCodeList(bidSectionCodeList);
        //项目编号
        setTenderProjectCode(project.getTenderProjectCode());
        //标段code列表
        setBidSectionCodes(bidSectionPushS);
        //招标编号
        setTenderCode("无");
        //公告名称
        setNoticeName(noticeDTO.getNoticeTitle());
        //公告内容文本
        setNoticeContent(StrUtil.isBlank(noticeDTO.getNoticeContent()) ? "无" : noticeDTO.getNoticeContent());
        //公告发布时间
        setNoticeSendTime(noticeDTO.getDeployTime().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        //公告发布媒介
        setNoticeMedia(noticeDTO.getMedium());
        //源URL
        setUrl(PushDataConfig.portalUrl + "noticeDetail?id=" + noticeDTO.getId() + "&bidTypeActive=" + (noticeDTO.getNoticeNature() > 1 ? 2 : 1));
        //公告性质
        setNoticeNature((noticeDTO.getNoticeNature() > 2 ? noticeDTO.getNoticeNature() : 9) + "");
        //公告类型
        setNoticeType("1");
        //公告获取开始时间
        BidSectionDTO bidSectionDTO = project.getSections().get(0);
        //招标文件/资格预审文件获取开始时间
        setDocGetStartTime(bidSectionDTO.getDocumentSaleStartTime() == null ? LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) : bidSectionDTO.getDocumentSaleStartTime().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) );
        //招标文件/资格预审文件获取截止时间
        setDocGetEndTime(bidSectionDTO.getDocumentSaleEndTime() == null ? LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) : bidSectionDTO.getDocumentSaleEndTime().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        //招标文件/资格预审文件获取方法
        setDocGetMethod("线上");
        //投标文件/资格预审申请文件递交截止时间
        setBidDocReferEndTime(bidSectionDTO.getClarificationSubmissionEndTime() == null ? LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) : bidSectionDTO.getDocumentSaleEndTime().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        //投标文件/资格预审申请文件递交方法
        setBidDocReferMethod("线上");
        //标文件/资格预审申请文件递交方法
        setBidUrl("详见招标文件");
        //sh
        //是否允许联合体投标
        setSyndicatedFlag(bidSectionDTO.getConsortiumBiddingFlag() == null || Integer.valueOf(2).equals( bidSectionDTO.getConsortiumBiddingFlag())? "0" : bidSectionDTO.getConsortiumBiddingFlag() + "");
        //延期
        setIsPostpone(Enums.equals(NoticeNatureEnum.DELAY,noticeDTO.getNoticeNature()) ? "1" : "0");
        //开标时间
        setBidOpenTime(bidSectionDTO.getOpenBidTime() == null ? LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) : bidSectionDTO.getOpenBidTime().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        setBidOpenMethod("线上");
        OrganizeInfo biddingOrganizeInfo = project.getBiddingOrganizeInfo();
        List<Map<String,Tenderer>> tenderers = CollUtil.list(false);
        HashMap<String, Tenderer> map = MapUtil.newHashMap(1);
        Tenderer tenderer = new Tenderer();
        tenderer.setTenderCodeType("05");
        tenderer.setTendererCode("/");
        tenderer.setTendererName("/");
        tenderer.setTendererAddress(biddingOrganizeInfo.getAddress());
        tenderer.setTendererContactor(biddingOrganizeInfo.getContact());
        tenderer.setTendererPhoneNumber(biddingOrganizeInfo.getContactInformation());
        tenderer.setTendererEmail(biddingOrganizeInfo.getMailbox());
        map.put("TENDERER",tenderer);
        tenderers.add(map);

        setTenderers(tenderers);
        OrganizeInfo agencyOrganizeInfo = project.getAgencyOrganizeInfo();
        List<Map<String,TenderAgency>> tenderAgencies = CollUtil.list(false);
        Map<String, TenderAgency> objectObjectHashMap = MapUtil.newHashMap(1);

        TenderAgency tenderAgency = new TenderAgency();
        tenderAgency.setTenderAgencyCodeType("05");
        tenderAgency.setTenderAgencyCode("/");
        tenderAgency.setTenderAgencyName("/");
        tenderAgency.setTenderAgencyAddress(agencyOrganizeInfo.getAddress());
        tenderAgency.setTenderAgencyContactor(agencyOrganizeInfo.getContact());
        tenderAgency.setTenderAgencyPhoneNumber(agencyOrganizeInfo.getContactInformation());
        tenderAgency.setTenderAgencyEmail(agencyOrganizeInfo.getMailbox());
        objectObjectHashMap.put("TENDER_AGENCY",tenderAgency);
        tenderAgencies.add(objectObjectHashMap);
        setTenderAgencies(tenderAgencies);
        //公示发布责任人
        setBulletinDuty(StrUtil.isEmpty(noticeDTO.getCreateName()) ? "代理机构" : noticeDTO.getCreateName());
        //交易平台数据验证责任人姓名
        setExaminerName(StrUtil.isEmpty(noticeDTO.getCreateName()) ? "项目经理" : noticeDTO.getCreateName());


        //附件列表
        List<Map<String,AttachmentSet>> attachmentSets = CollUtil.list(false);
        Map<String, AttachmentSet> attachmentMap = MapUtil.newHashMap(1);
        attachmentMap.put("ATTACHMENT",attachmentSet);
        attachmentSets.add(attachmentMap);
        setAttachmentSets(attachmentSets);

        //交易平台或发布工具标识码
        setTradePlat(ConstantUtil.SOURCE_SYSTEM_ID);
        //公共服务平台标识码
        setPubServicePlatCode(ConstantUtil.TARGET_SYSTEM_ID_TEST);
        //时间戳
        setSubmitTimestamp(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
    }
}
